package com.citydo.webrtcspringboot.transfer.mqtt;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Random;

@Configuration
public class MqttConfig {
    @Value("tcp://172.16.1.6:1883")
    public String broker;

    //配置类，用于配置 MQTT 连接
    @Bean
    public MqttConnectOptions mqttConnectOptions() {
        MqttConnectOptions options = new MqttConnectOptions();
        options.setServerURIs(new String[]{broker});
        // Set other connection options as needed
        return options;
    }
    @Bean
    public IMqttAsyncClient  mqttClient() throws MqttException {
        String clientId = String.valueOf(new Random().nextInt(10000000));
        return new MqttAsyncClient(broker, clientId);
    }
//    @Bean
//    public IMqttClient mqttClient(MqttConnectOptions mqttConnectOptions) throws MqttException {
//        return new MqttAsyncClient("tcp://172.16.1.6:1883", String.valueOf(new Random().nextInt(10)), new MemoryPersistence());
//    }
    public void tMain(){
        String broker = "tcp://broker.example.com:1883"; // 替换为你的 MQTT 代理地址
        String clientId = "JavaMqttClient";
        String topic = "test/topic";

        try {
            MqttClient client = new MqttClient(broker, clientId);
            MqttConnectOptions options = new MqttConnectOptions();
            options.setCleanSession(true);

            client.connect(options);

            // 订阅主题
            client.subscribe(topic);

            // 发布消息
            String messageContent = "Hello, MQTT!";
            MqttMessage message = new MqttMessage(messageContent.getBytes());
            client.publish(topic, message);

            // 设置回调处理接收到的消息
            client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {
                    System.out.println("Connection lost: " + cause.getMessage());
                }

                @Override
                public void messageArrived(String topic, MqttMessage message) throws Exception {
                    System.out.println("Received message from topic: " + topic);
                    System.out.println("Message: " + new String(message.getPayload()));
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    System.out.println("Delivery complete: " + token.getMessageId());
                }
            });

            // 等待一段时间以接收消息
            Thread.sleep(5000);

            // 断开连接
            client.disconnect();

        } catch (MqttException | InterruptedException e) {
            e.printStackTrace();
        }
    }

}
